from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser, OAuthSinaUser

#     access_tooken
#     sms_code
#     根据手机号判断用户是否注册
from oauth.utils import check_access_token
from users.models import User


class OAuthQQUserSerializers(serializers.Serializer):

    access_token = serializers.CharField(label='操作凭证',required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$',required=True)
    password = serializers.CharField(label='密码', max_length=20, min_length=8,required=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,required=True)

    def validate(self, attrs):
        # 1.验证 access_token
        access_token = attrs['access_token']
        openid = check_access_token(access_token)
        if openid is None:
            raise serializers.ValidationError('openid不存在')
        attrs['openid'] = openid
        # 2.验证短信验证码
        code = attrs['sms_code']
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')
        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')
        # 3.判断手机号是否注册
        # 根据手机号查询用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 说明此手机号没有注册
            # 创建一个用户
            # 因为此vaildate
            pass
        else:
            # 说明此手机号已经注册
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码不正确')
            attrs['user'] = user
        return attrs
    """
    数据的流向
    data --> attrs --> validated_data
    """
    def create(self, validated_data):
        user= validated_data.get('user')
        openid = validated_data.get('openid')
        if user is None:
            # 说明没有注册过,我们需要手动创建一个用户
            user = User.objects.create(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password'),
            )
            user.set_password(validated_data['password'])
            user.save()
        qquser = OAuthQQUser.objects.create(
            user= user,
            openid = validated_data.get('openid')
        )
        return qquser


class OAuthWeiBoUserSerializer(serializers.Serializer):
    mobile = serializers.RegexField(regex='1[3-9]\d{9}', label='手机号', required=True)
    password = serializers.CharField(label='密码', required=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, required=True)
    access_token = serializers.CharField()

    def validate(self, attrs):
        access_token = attrs.get('access_token')
        if access_token is None:
            raise serializers.ValidationError('绑定时效过期')
        attrs['access_token']=access_token
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile)
        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')

        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass

        else:
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        user = validated_data.get('user')
        access_token = validated_data.get('access_token')
        if user is None:
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

            weibo_user = OAuthSinaUser.objects.create(
            user=user,
            access_token=access_token
            )
            return weibo_user
